package com.self.match.model;

import com.self.common.enums.OrderDirection;
import com.self.common.param.Order;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * 交易的盘口数据,以后前端可以查询该数据
 */
@Data
public class TradePlate {

    /**
     * 判断数据的详情
     */
    private LinkedList<DepthItemVo> items = new LinkedList<DepthItemVo>();
    /**
     * 最大支持的深度
     */
    private int maxDepth = 100;

    /**
     * 订单的方向
     */
    private OrderDirection direction;

    /**
     * 交易对
     */
    private String symbol;

    public TradePlate(String symbol, OrderDirection direction) {
        this.symbol = symbol;
        this.direction = direction;
    }


    /**
     * 添加订单数据到盘口数据里面
     *  新增一个委托单时，没有全部成交，需要展示到盘口中
     *
     * @param order
     */
    public void add(Order order) {
        if (order.getOrderDirection() != direction){
            return;
        }
        int i = 0;
        for (i= 0; i< items.size(); i++){
            //买方，按照价格从大到小
            //买方，按照价格从小到达
            DepthItemVo itemVo = items.get(i);
            if((order.getOrderDirection() == OrderDirection.BUY && order.getPrice().compareTo(itemVo.getPrice()) < 0) ||
                  (order.getOrderDirection() == OrderDirection.SELL && order.getPrice().compareTo(itemVo.getPrice()) > 0)){
                 continue;
            }else if (order.getPrice().compareTo(itemVo.getPrice()) == 0){
                itemVo.setVolume(itemVo.getVolume().add(order.getAmount().subtract(order.getTradedAmount())));
            }else{
                break;
            }
        }
        if (i < maxDepth){
            DepthItemVo depthItemVo = new DepthItemVo();
            depthItemVo.setPrice(order.getPrice());
            depthItemVo.setVolume(order.getAmount().subtract(order.getTradedAmount()));
            items.add(i,depthItemVo);
        }
    }


    /**
     * 从盘口里面移除订单
     *
     * @param order
     */
    public void remove(Order order) {
        // order.getAmount().subtract(order.getTradedAmount() 成交的数量
        remove(order, order.getAmount().subtract(order.getTradedAmount()));
    }

    /***
     * 从盘口里面移除数据
     * @param order
     * @param amount
     */
    public void remove(Order order, BigDecimal amount) {
        if (items.size() == 0){
            return;
        }
        if (order.getOrderDirection() != direction){
            return;
        }
        //价格相同可以删除
        Iterator<DepthItemVo> iterator = items.iterator();
        while (iterator.hasNext()){
            DepthItemVo next = iterator.next();
            if(order.getPrice().compareTo(next.getPrice()) == 0){
                next.setVolume(next.getVolume().subtract(amount));
                if (next.getVolume().compareTo(BigDecimal.ZERO) < 0){
                    iterator.remove();
                }
            }
        }

    }
}
